package com.company.project.common.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.company.project.common.pojo.AjaxResult;
import com.company.project.common.utils.AppUtil;
import com.company.project.common.pojo.ServiceCode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)//400
    @ResponseBody
    public AjaxResult validateErrorHandler(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            List<FieldError> errorList = e.getBindingResult().getFieldErrors();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("field", errorList.get(0).getField());
            map.put("errorMsg", errorList.get(0).getDefaultMessage());
            logger.info(map.toString());
            return AppUtil.ajaxResult(ServiceCode.CODE_403, "参数错误！！！" , map);
        } else {
        	e.printStackTrace();
        	return AppUtil.ajaxResult(ServiceCode.CODE_500, "服务器错误");
        }
    }

    /**
     * Exception to be thrown when validation on an argument annotated with {@code @Valid} fails.
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public AjaxResult handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        if (ex.getBindingResult().hasErrors()) {
            List<FieldError> errorList = ex.getBindingResult().getFieldErrors();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("field", errorList.get(0).getField());
            map.put("errorMsg", errorList.get(0).getDefaultMessage());
            logger.info(map.toString());
            return AppUtil.ajaxResult(ServiceCode.CODE_403, "参数错误！！！" , map);
        } else {
        	ex.printStackTrace();
        	return AppUtil.ajaxResult(ServiceCode.CODE_500, "服务器错误");
        }
    }

}